package com.smart.sms.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import com.qf.common.result.ResponseResultCode;
import com.smart.sms.common.ex.SmsException;
import com.smart.sms.config.AliSmsConfigProperties;
import com.smart.sms.service.SmsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    private Client client;
    @Resource
    private AliSmsConfigProperties configProperties;

    /**
     * @param phone
     * @param code
     * @return
     */
    @Override
    public void send(String phone, String code) {
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setSignName(configProperties.getSignName());
        sendSmsRequest.setTemplateCode(configProperties.getTemplateCode());
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        runtimeOptions.setAutoretry(configProperties.getAutoRetry());
        runtimeOptions.setConnectTimeout(configProperties.getConnectTimeout());
        runtimeOptions.setReadTimeout(configProperties.getReadTimeout());
        try {
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtimeOptions);
            if (sendSmsResponse.getStatusCode() == 200) {
                // 将发送信息保存在数据库
            } else {
                throw new SmsException(ResponseResultCode.SYS_ERROR);
            }
        } catch (Exception e) {
            throw new SmsException(ResponseResultCode.SYS_ERROR);
        }

    }
}
